import { login, logout, getInfo, getLastNotice } from '@/api/common/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import store from '@/store'

const state = {
  token: getToken(),
  uId: '',
  userId: '',
  name: '',
  hasUserInfo: '0',
  loginUserName: '',
  userName: '',
  avatar: '',
  introduction: '',
  phone: '',
  authList: [],
  browserNotification: '',
  windowsNotification: '',
  notificationVoice: '',
  messageNum: 0,
  approvalNum: 0,
  foreverUseStatus: 2,
  loginTag: 0, // 标识是否刚登录进来
  logo: '',
  companyId: '',
  companyName: '',
  isAdmin: '',
  firstLogin: '',
  pageTitle: '',
  expirationTime: '', // 到期时间
  roles: [],
  permissions: [],
  poster: {},
  unionId: '',
  authStatus: '',
  pointsCashStatus: '',
  pointsGetStatus: '',
  codeStatus: ''
}

const mutations = {
  SET_pointsCashStatus: (state, pointsCashStatus) => {
    state.pointsCashStatus = pointsCashStatus
  },
  SET_pointsGetStatus: (state, pointsGetStatus) => {
    state.pointsGetStatus = pointsGetStatus
  },
  SET_unionId: (state, unionId) => {
    state.unionId = unionId
  },
  SET_HASUSERINFO: (state, hasUserInfo) => {
    state.hasUserInfo = hasUserInfo
  },
  SET_LoginUserName: (state, loginUserName) => {
    state.loginUserName = loginUserName
  },
  SET_USERID: (state, userId) => {
    state.uId = userId
    state.userId = userId
  },
  SET_roles: (state, roles) => {
    state.roles = roles
  },
  SET_permissions: (state, permissions) => {
    state.permissions = permissions
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_USERNAME: (state, userName) => {
    state.name = userName
    state.userName = userName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_AUTH: (state, authList) => {
    state.authList = authList
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_browserNotification: (state, browserNotification) => {
    state.browserNotification = browserNotification
  },
  SET_windowsNotification: (state, windowsNotification) => {
    state.windowsNotification = windowsNotification
  },
  SET_notificationVoice: (state, notificationVoice) => {
    state.notificationVoice = notificationVoice
  },
  SET_companyId: (state, companyId) => {
    state.companyId = companyId
  },
  SET_companyName: (state, companyName) => {
    state.companyName = companyName
  },
  SET_MESSAGENUM: (state, messageNum) => {
    state.messageNum = messageNum
  },
  SET_APPROVALNUM: (state, approvalNum) => {
    state.approvalNum = approvalNum
  },
  SET_LOGO: (state, logo) => {
    state.logo = logo
  },
  SET_COMPANYNAME: (state, companyName) => {
    state.companyName = companyName || 'CASCADE'
  },
  SET_PAGETITLE: (state, pageTitle) => {
    state.pageTitle = pageTitle || 'CASCADE'
  },
  SET_expirationTime: (state, expirationTime) => {
    state.expirationTime = expirationTime
  },
  SET_isAdmin: (state, isAdmin) => {
    state.isAdmin = isAdmin
  },
  SET_firstLogin: (state, firstLogin) => {
    state.firstLogin = firstLogin
  },
  SET_loginTag: (state, loginTag) => {
    state.loginTag = loginTag
  },
  SET_foreverUseStatus: (state, foreverUseStatus) => {
    state.foreverUseStatus = foreverUseStatus
  },
  SET_authStatus: (state, authStatus) => {
    state.authStatus = authStatus
  },
  SET_codeStatus: (state, codeStatus) => {
    state.codeStatus = codeStatus
  },
  SET_poster: (state, poster) => {
    state.poster = poster
  }
}

const actions = {
  getPointsCashStatus(context, value) {
    context.commit('SET_pointsCashStatus', value)
  },
  getPointsGetStatus(context, value) {
    context.commit('SET_pointsGetStatus', value)
  },
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      const { username, password } = userInfo
      login({ username: username, password: password }).then(response => {
        if (response && response.token) {
          commit('SET_TOKEN', response.token) // token存入state
          setToken(response.token) // token存入cookie
          commit('SET_loginTag', new Date().getTime())
          resolve(response)
        } else {
          reject()
        }
      })
    })
  },
  // get  user codeStatus
  getCodeStatus({ commit }, codeStatus) {
    commit('SET_codeStatus', codeStatus)
  },
  // get user info
  getInfo({ commit, state }) {
    store.state.app.loadingFull = true
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        // if (response.user.firstLogin) {
        //   this.$layer.iframe({// 弹框
        //     content: {
        //       content: resetPassword, // 传递的组件对象
        //       parent: this, // 当前的vue对象
        //       data: {}// props
        //     },
        //     area: ['880px', '700px'],
        //     title: '新增合同评审单', // 标题
        //     shadeClose: false // 点击遮罩是否关闭
        //   })
        // }
        const { roles } = response
        const { userId, realName, userName, avatar, companyId, isAdmin, firstLogin, unionId, poster } = response.user
        // authList 不能为空
        // if ((!roles || roles.length <= 0)) {
        //   reject('无权访问')
        // }
        commit('SET_authStatus', response.company.authStatus || '')
        commit('SET_unionId', unionId || '')
        commit('SET_roles', response.roles || '')
        commit('SET_permissions', response.permissions || '')
        commit('SET_USERID', userId)
        commit('SET_companyId', companyId)
        commit('SET_LoginUserName', userName)
        commit('SET_USERNAME', realName)
        commit('SET_isAdmin', isAdmin)
        commit('SET_codeStatus', response.smsEnabled)
        commit('SET_firstLogin', firstLogin)
        commit('SET_PHONE', response.user.phonenumber)
        commit('SET_poster', response.poster)
        // commit('SET_AVATAR', avatar || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        // commit('SET_AVATAR', avatar || 'https://nfs.cascadeiot.com/public/jlink2.png')
        commit('SET_AVATAR', avatar || 'https://nfs.cascadeiot.com/public/default_avatar.svg')
        commit('SET_HASUSERINFO', '1')

        if (response.company) {
          const { logoUrl, expirationTime, name, foreverUseStatus } = response.company
          commit('SET_LOGO', logoUrl)
          commit('SET_expirationTime', expirationTime)
          commit('SET_companyName', name)
          commit('SET_foreverUseStatus', foreverUseStatus)
        }

        setTimeout(() => {
          getLastNotice({ userId: userId })
        }, 1500)
        resolve(response)
      }).catch(error => {
        store.state.app.loadingFull = false
        reject(error)
      }).finally(() => {
      })
    })
  },

  // user logout
  async logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_AUTH', [])
        commit('SET_USERNAME', '')
        commit('SET_HASUSERINFO', '0')
        removeToken()
        resetRouter()

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_AUTH', [])
      removeToken()
      resolve()
    })
  },

  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { authList } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', authList, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
  setCompany({ commit }, data) {
    commit('SET_LOGO', data.logo)
    commit('SET_COMPANYNAME', data.companyName)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
